package pyip.lib.javalearn.classloader.load;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class CopyOfContextClassLoaderDemo {

    public static void main(String[] args) throws MalformedURLException, ClassNotFoundException {
        System.out.println("MainClass getClassLoader: " + CopyOfContextClassLoaderDemo.class.getClassLoader());
        System.out.println("MainClass getContextClassLoader: " + Thread.currentThread().getContextClassLoader());
        Thread innerThread1 = new InnerThread1();
        innerThread1.start();
    }

    private static class InnerThread1 extends Thread {
        @Override
        public void run() {
            try {

                URL[] urls = new URL[1];
                urls[0] = new URL("jar:file:/E:/GoogleCode/platform-components/trunk/SourceCode/component-core/target/component-core-1.0.jar!/");
                URLClassLoader urlClassLoader = new URLClassLoader(urls);

                this.setContextClassLoader(urlClassLoader);

                Class<?> clazz = urlClassLoader.loadClass("classloader.load.A");
                // Class<?> clazz = Class.forName("classloader.load.A", false, urlClassLoader);

                System.out.println("InnerThread1 getClassLoader: " + ClassA.class.getClassLoader());
                System.out.println("InnerThread1 getClassLoader: " + clazz.getClassLoader());
                System.out.println("InnerThread1 getContextClassLoader: " + Thread.currentThread().getContextClassLoader());

                Thread innerThread2 = new InnerThread2();
                innerThread2.start();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private static class InnerThread2 extends Thread {
        @Override
        public void run() {
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                Class<?> clazzB = classLoader.loadClass("classloader.load.B");
                System.out.println("InnerThread2 getClassLoader: " + clazzB.getClassLoader());
                System.out.println("InnerThread2 getContextClassLoader: " + Thread.currentThread().getContextClassLoader());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
